package org.dxy.ui;

import lombok.extern.log4j.Log4j2;
import org.dxy.domain.game.adapter.event.EventQueue;
import org.dxy.domain.game.command.GameStartCommand;
import org.dxy.domain.game.command.SideSwapCommand;
import org.dxy.domain.game.database.GameDatabase;
import org.dxy.domain.game.model.aggregate.GameAggregate;
import org.dxy.domain.game.model.entity.PieceEntity;
import org.dxy.types.enums.PieceColorEnum;
import org.dxy.types.enums.PieceNameEnum;
import org.jdesktop.swingx.border.DropShadowBorder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;

import static org.dxy.types.enums.PieceColorEnum.BLACK;
import static org.dxy.types.enums.PieceColorEnum.RED;

@Log4j2
@Component
public class GameUI extends JFrame implements ActionListener, MouseListener, Runnable {
    private final EventQueue eventQueue;
    private final GameAggregate gameAggregate;
    private final GameDatabase gameDatabase;
    private PieceEntity clickedPiece;
    private Thread gameThread;
    private Container container;
    private final JToolBar jToolBar = new JToolBar();
    private List<PieceEntity> pieceEntityList; // 棋子列表
    private int clickedIndex;
    private Timer blinkTimer; // 控制闪烁的 Timer
    private JButton timeButton;
    private Timer timer;
    private int timeLeft = 20; // 每次从 20 开始
    private JButton pauseButton;
    private JButton swapSideButton;
    private JButton undoButton;
    private JButton drawButton;
    private JButton surrenderButton;
    private JButton resetButton;
    private JButton endButton;
    private JLabel backgroundJLabel;
    private static final int WINDOW_WIDTH = 570; // 窗口宽度
    private static final int WINDOW_HEIGHT = 720; // 窗口高度
    private static final int PIECE_SIZE = 58; // 棋子大小
    private static final int BOARD_OFFSET_X = 20; // 棋盘偏移量 X
    private static final int BOARD_OFFSET_Y = 20; // 棋盘偏移量 Y
    private PieceColorEnum currentTurn = RED; // 默认红方先手
    private JButton currentTurnButton; // 添加当前回合显示按钮
    private boolean isPaused = false; // 添加暂停标志

    // 添加悔棋相关的数据结构
    private static class MoveRecord {
        PieceEntity piece;
        int fromX, fromY;
        int toX, toY;
        PieceEntity capturedPiece;

        MoveRecord(PieceEntity piece, int fromX, int fromY, int toX, int toY, PieceEntity capturedPiece) {
            this.piece = piece;
            this.fromX = fromX;
            this.fromY = fromY;
            this.toX = toX;
            this.toY = toY;
            this.capturedPiece = capturedPiece;
        }
    }

    private java.util.Stack<MoveRecord> moveHistory = new java.util.Stack<>();

    // 构造器注入
    @Autowired
    public GameUI(EventQueue eventQueue, GameAggregate gameAggregate, GameDatabase gameDatabase) {
        this.eventQueue = eventQueue;
        this.gameAggregate = gameAggregate;
        this.gameDatabase = gameDatabase;
    }


    public void init() {
        // 初始化窗口
        setTitle("中国象棋");
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示
        container = this.getContentPane();
        container.setLayout(null); // 禁用布局管理器

        // 初始化工具栏
        initToolBar();

        // 初始化棋子
        initPieces();

        // 设置背景图片
        setBackgroundImage();

        // 初始化倒计时
        startCountdown();

        // 显示窗口
        this.setVisible(true);
    }

    // **封装背景图设置逻辑**
    private void setBackgroundImage() {
        if (backgroundJLabel != null) {
            container.remove(backgroundJLabel);
        }
        ImageIcon imageIcon = new ImageIcon(getClass().getClassLoader().getResource("images/main.gif"));
        backgroundJLabel = new JLabel(imageIcon);
        backgroundJLabel.setBounds(0, 0, imageIcon.getIconWidth(), imageIcon.getIconHeight());
        backgroundJLabel.addMouseListener(this);
        container.add(backgroundJLabel);
    }

    // **封装棋子初始化逻辑**
    private void initPieces() {
        GameStartCommand gameStartCommand = GameStartCommand.builder().gameId(1L).build();
        gameAggregate.handle(eventQueue, gameStartCommand);
        updatePieces();
    }

    // **重用 updatePieces() 进行棋子更新**
    private void updatePieces() {
        pieceEntityList = gameDatabase.getAllPieces();

        // **移除旧的棋子（但不影响其他 UI 组件）**
        for (java.awt.Component component : container.getComponents()) {
            if (component instanceof PieceEntity) {
                container.remove(component);
            }
        }


        pieceEntityList.forEach(pieceEntity -> {
            ImageIcon imageIcon = new ImageIcon(getClass().getClassLoader().getResource(pieceEntity.getImagePath()));
            pieceEntity.setIcon(imageIcon);
            int pixelX = pieceEntity.getRow() * PIECE_SIZE + BOARD_OFFSET_X;
            int pixelY = pieceEntity.getColumn() * PIECE_SIZE + BOARD_OFFSET_Y;
            pieceEntity.setBounds(pixelX, pixelY, PIECE_SIZE, PIECE_SIZE);

            container.add(pieceEntity);
            pieceEntity.addMouseListener(this);
        });
    }

    // **倒计时封装**
    private void startCountdown() {
        if (timer != null && timer.isRunning()) {
            timer.stop();
        }
        timeLeft = 20;
        timeButton.setText("倒计时: " + timeLeft);

        timer = new Timer(1000, e -> {
            timeLeft--;
            timeButton.setText("倒计时: " + timeLeft);
            if (timeLeft <= 0) {
                timer.stop();
                startCountdown();
            }
        });
        timer.start();
    }

    // **优化工具栏初始化**
    private void initToolBar() {
        jToolBar.setLayout(new GridLayout(2, 8));
        jToolBar.setFloatable(false);

        pauseButton = new JButton("暂停");
        swapSideButton = new JButton("换边");
        undoButton = new JButton("悔棋");
        drawButton = new JButton("和棋");
        surrenderButton = new JButton("投降");
        resetButton = new JButton("重新开始");
        endButton = new JButton("退出游戏");
        timeButton = new JButton("倒计时: 20");
        currentTurnButton = new JButton("当前回合: 红方"); // 初始化当前回合按钮
        
        timeButton.setEnabled(false);
        currentTurnButton.setEnabled(false); // 设置为不可点击
        currentTurnButton.setForeground(Color.RED); // 设置文字颜色
        
        pauseButton.addActionListener(this);
        swapSideButton.addActionListener(this);
        undoButton.addActionListener(this);
        drawButton.addActionListener(this);
        surrenderButton.addActionListener(this);
        resetButton.addActionListener(this);
        endButton.addActionListener(this);

        jToolBar.add(currentTurnButton); // 添加当前回合按钮
        jToolBar.add(pauseButton);
        jToolBar.add(swapSideButton);
        jToolBar.add(undoButton);
        jToolBar.add(drawButton);
        jToolBar.add(surrenderButton);
        jToolBar.add(resetButton);
        jToolBar.add(endButton);
        jToolBar.add(timeButton);

        jToolBar.setBounds(0, 620, WINDOW_WIDTH, 50);
        container.add(jToolBar);
    }

    // **封装暂停/继续计时**
    private void toggleTimer() {
        if (timer.isRunning()) {
            timer.stop();
            pauseButton.setText("继续");
            isPaused = true; // 设置暂停标志
        } else {
            timer.start();
            pauseButton.setText("暂停");
            isPaused = false; // 取消暂停标志
        }
    }

    // **优化换边逻辑**
    private void swapSides() {
        Long gameId = gameAggregate.getGameId();
        Long currentPlayerId = gameAggregate.getCurrentPlayerId();
        SideSwapCommand sideSwapCommand = SideSwapCommand.builder().gameId(gameId).playerId(currentPlayerId).build();
        gameAggregate.handle(eventQueue, sideSwapCommand);

        // 切换当前回合
        currentTurn = (currentTurn == RED) ? BLACK : RED;
        updateTurnDisplay(); // 更新回合显示

        // 只更新棋子，不影响其他 UI 组件
        updatePieces();

        // 设置背景图片
        setBackgroundImage();

        // 重新绘制界面
        container.revalidate();
        container.repaint();
    }

    // 更新当前回合显示
    private void updateTurnDisplay() {
        String turnText = currentTurn == RED ? "当前回合: 红方" : "当前回合: 黑方";
        Color textColor = currentTurn == RED ? Color.RED : Color.BLACK;
        currentTurnButton.setText(turnText);
        currentTurnButton.setForeground(textColor);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(pauseButton)) {
            this.toggleTimer();
        } else if (e.getSource().equals(swapSideButton)) {
            this.swapSides();
        } else if (e.getSource().equals(undoButton)) {
            this.undoMove();
        } else if (e.getSource().equals(drawButton)) {
            this.offerDraw();
        } else if (e.getSource().equals(surrenderButton)) {
            this.surrender();
        } else if (e.getSource().equals(resetButton)) {
            this.resetGame();
        } else if (e.getSource().equals(endButton)) {
            this.endGame();
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // 如果游戏暂停，不处理任何点击事件
        if (isPaused) {
            JOptionPane.showMessageDialog(this, 
                "游戏已暂停，请点击继续后再操作！", 
                "提示", 
                JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        if (e.getSource().equals(backgroundJLabel)) {
            Point point = e.getPoint();
            int targetX = getPieceAtPointX(point);
            int targetY = getPieceAtPointY(point);
            if (clickedPiece != null) {
                // 检查移动是否合法
                if (isValidMove(clickedPiece, targetX, targetY)) {
                    // 停止闪烁
                    if (blinkTimer != null && blinkTimer.isRunning()) {
                        blinkTimer.stop();
                    }
                    // 移动棋子
                    movePiece(clickedPiece, targetX, targetY);
                    // 切换回合
                    currentTurn = (currentTurn == RED) ? BLACK : RED;
                    updateTurnDisplay(); // 更新回合显示
                    clickedPiece = null;
                }
            }
        } else {
            PieceEntity pieceEntity = (PieceEntity) e.getSource();
            if (pieceEntity != null) {
                // 如果已经选中了一个棋子
                if (clickedPiece != null) {
                    // 如果点击的是对方的棋子，尝试吃子
                    if (pieceEntity.getPieceColorEnum() != clickedPiece.getPieceColorEnum()) {
                        // 检查移动是否合法
                        if (isValidMove(clickedPiece, pieceEntity.getRow(), pieceEntity.getColumn())) {
                            // 停止闪烁
                            if (blinkTimer != null && blinkTimer.isRunning()) {
                                blinkTimer.stop();
                            }
                            // 执行吃子移动
                            movePiece(clickedPiece, pieceEntity.getRow(), pieceEntity.getColumn());
                            // 切换回合
                            currentTurn = (currentTurn == RED) ? BLACK : RED;
                            updateTurnDisplay(); // 更新回合显示
                            clickedPiece = null;
                            return;
                        }
                    }
                }

                // 检查是否是当前回合的棋子
                if (pieceEntity.getPieceColorEnum() != currentTurn) {
                    // 添加提示信息
                    String currentSide = currentTurn == RED ? "红方" : "黑方";
                    JOptionPane.showMessageDialog(this, 
                        "现在是" + currentSide + "的回合！", 
                        "提示", 
                        JOptionPane.INFORMATION_MESSAGE);
                    return; // 如果不是当前回合的棋子，直接返回
                }

                // 如果之前有选中的棋子，先停止它的闪烁
                if (clickedPiece != null && blinkTimer != null && blinkTimer.isRunning()) {
                    blinkTimer.stop();
                    clickedPiece.setVisible(true);
                }

                // 如果点击的是同一个棋子，取消选择
                if (pieceEntity == clickedPiece) {
                    clickedPiece = null;
                    return;
                }

                // 选中新的棋子
                clickedPiece = pieceEntity;

                // 创建新的闪烁效果
                if (blinkTimer != null && blinkTimer.isRunning()) {
                    blinkTimer.stop();
                }
                blinkTimer = new Timer(200, evt -> {
                    clickedPiece.setVisible(!clickedPiece.isVisible());
                });
                blinkTimer.start();
            }
        }
    }

    // 点击其他位置停止闪烁
    @Override
    public void mousePressed(MouseEvent e) {
        if (blinkTimer != null && blinkTimer.isRunning()) {
            blinkTimer.stop();
            clickedPiece.setVisible(true); // 恢复显示
//            clickedPiece = null;
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }


    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void run() {
    }


    private int getPieceAtPointX(Point point) {
        int clickedX = point.x; // 获取点击的 X 坐标
        int x = (clickedX - BOARD_OFFSET_X) / PIECE_SIZE; // 转换为棋盘的 X 坐标
        return x;
    }

    private int getPieceAtPointY(Point point) {
        int clickedY = point.y; // 获取点击的 Y 坐标
        int y = (clickedY - BOARD_OFFSET_Y) / PIECE_SIZE; // 转换为棋盘的 X 坐标
        return y;
    }

    private boolean isValidMove(PieceEntity piece, int targetX, int targetY) {
        int currentX = piece.getRow();
        int currentY = piece.getColumn();
        PieceNameEnum pieceName = piece.getPieceName();

        // 检查目标位置是否有己方棋子
        PieceEntity targetPiece = getPieceAtPosition(targetX, targetY);
        if (targetPiece != null && targetPiece.getPieceColorEnum().equals(piece.getPieceColorEnum())) {
            return false;
        }

        switch (pieceName) {
            case ROOK:
                return isValidRookMove(currentX, currentY, targetX, targetY);
            case KNIGHT:
                return isValidKnightMove(currentX, currentY, targetX, targetY);
            case MINISTER:
            case ELEPHANT:
                return isValidBishopMove(currentX, currentY, targetX, targetY, piece.getPieceColorEnum());
            case ADVISOR:
                return isValidAdvisorMove(currentX, currentY, targetX, targetY, piece.getPieceColorEnum());
            case KING:
            case GENERAL:
                return isValidKingMove(currentX, currentY, targetX, targetY, piece.getPieceColorEnum());
            case CANNON:
                return isValidCannonMove(currentX, currentY, targetX, targetY);
            case PAWN:
            case SOLDIER:
                return isValidPawnMove(currentX, currentY, targetX, targetY, piece.getPieceColorEnum());
            default:
                return false;
        }
    }

    private boolean isValidRookMove(int currentX, int currentY, int targetX, int targetY) {
        // 车只能直线移动
        if (currentX != targetX && currentY != targetY) {
            return false;
        }

        // 检查路径上是否有其他棋子
        if (currentX == targetX) {
            int minY = Math.min(currentY, targetY);
            int maxY = Math.max(currentY, targetY);
            for (int y = minY + 1; y < maxY; y++) {
                if (getPieceAtPosition(currentX, y) != null) {
                    return false;
                }
            }
        } else {
            int minX = Math.min(currentX, targetX);
            int maxX = Math.max(currentX, targetX);
            for (int x = minX + 1; x < maxX; x++) {
                if (getPieceAtPosition(x, currentY) != null) {
                    return false;
                }
            }
        }
        return true;
    }

    private boolean isValidKnightMove(int currentX, int currentY, int targetX, int targetY) {
        // 马走日字
        int deltaX = Math.abs(targetX - currentX);
        int deltaY = Math.abs(targetY - currentY);
        if (!((deltaX == 2 && deltaY == 1) || (deltaX == 1 && deltaY == 2))) {
            return false;
        }

        // 检查马脚
        // 获取马脚的位置
        int legX = currentX;
        int legY = currentY;

        if (deltaX == 2) {
            // 横向移动两格时，马脚在移动方向上
            legX = currentX + (targetX - currentX) / 2;
            legY = currentY;
        } else if (deltaY == 2) {
            // 纵向移动两格时，马脚在移动方向上
            legX = currentX;
            legY = currentY + (targetY - currentY) / 2;
        }

        // 检查马脚位置是否有棋子
        return getPieceAtPosition(legX, legY) == null;
    }

    private boolean isValidBishopMove(int currentX, int currentY, int targetX, int targetY, PieceColorEnum pieceColor) {
        // 相/象只能走田字
        if (Math.abs(targetX - currentX) != 2 || Math.abs(targetY - currentY) != 2) {
            return false;
        }

        // 不能过河
        if (pieceColor.equals(RED) && targetY > 4 || pieceColor.equals(BLACK) && targetY < 5) {
            return false;
        }

        // 检查象心
        int centerX = (currentX + targetX) / 2;
        int centerY = (currentY + targetY) / 2;
        return getPieceAtPosition(centerX, centerY) == null;
    }

    private boolean isValidAdvisorMove(int currentX, int currentY, int targetX, int targetY, PieceColorEnum pieceColor) {
        // 士/仕只能在九宫格内斜走一格
        if (Math.abs(targetX - currentX) != 1 || Math.abs(targetY - currentY) != 1) {
            return false;
        }

        // 检查是否在九宫格内
        if (pieceColor.equals(RED)) {
            return targetX >= 3 && targetX <= 5 && targetY >= 0 && targetY <= 2;
        } else {
            return targetX >= 3 && targetX <= 5 && targetY >= 7 && targetY <= 9;
        }
    }

    private boolean isValidKingMove(int currentX, int currentY, int targetX, int targetY, PieceColorEnum pieceColor) {
        // 将/帅只能在九宫格内走一格
        if (Math.abs(targetX - currentX) + Math.abs(targetY - currentY) != 1) {
            return false;
        }

        // 检查是否在九宫格内
        if (pieceColor.equals(RED)) {
            return targetX >= 3 && targetX <= 5 && targetY >= 0 && targetY <= 2;
        } else {
            return targetX >= 3 && targetX <= 5 && targetY >= 7 && targetY <= 9;
        }
    }

    private boolean isValidCannonMove(int currentX, int currentY, int targetX, int targetY) {
        // 炮只能直线移动
        if (currentX != targetX && currentY != targetY) {
            return false;
        }

        int pieceCount = 0;
        PieceEntity targetPiece = getPieceAtPosition(targetX, targetY);

        // 计算路径上的棋子数
        if (currentX == targetX) {
            int minY = Math.min(currentY, targetY);
            int maxY = Math.max(currentY, targetY);
            for (int y = minY + 1; y < maxY; y++) {
                if (getPieceAtPosition(currentX, y) != null) {
                    pieceCount++;
                }
            }
        } else {
            int minX = Math.min(currentX, targetX);
            int maxX = Math.max(currentX, targetX);
            for (int x = minX + 1; x < maxX; x++) {
                if (getPieceAtPosition(x, currentY) != null) {
                    pieceCount++;
                }
            }
        }

        // 炮的移动规则：移动时不能有棋子，吃子时必须翻过一个棋子
        if (targetPiece == null) {
            return pieceCount == 0;
        } else {
            return pieceCount == 1;
        }
    }

    private boolean isValidPawnMove(int currentX, int currentY, int targetX, int targetY, PieceColorEnum pieceColor) {
        int deltaX = Math.abs(targetX - currentX);
        int deltaY = targetY - currentY;

        if (pieceColor.equals(RED)) {
            // 红方兵
            if (currentY < 5) {
                // 未过河，只能向前
                return deltaX == 0 && deltaY == 1;
            } else {
                // 过河后，可以向前或左右
                return (deltaX == 0 && deltaY == 1) || (deltaY == 0 && deltaX == 1);
            }
        } else {
            // 黑方卒
            if (currentY > 4) {
                // 未过河，只能向前
                return deltaX == 0 && deltaY == -1;
            } else {
                // 过河后，可以向前或左右
                return (deltaX == 0 && deltaY == -1) || (deltaY == 0 && deltaX == 1);
            }
        }
    }

    private void undoMove() {
        if (moveHistory.isEmpty()) {
            JOptionPane.showMessageDialog(this, 
                "没有可以悔棋的步骤！", 
                "提示", 
                JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        MoveRecord lastMove = moveHistory.pop();
        
        // 恢复移动的棋子到原位置
        lastMove.piece.setRow(lastMove.fromX);
        lastMove.piece.setColumn(lastMove.fromY);
        lastMove.piece.setLocation(calculatePixelX(lastMove.fromX), calculatePixelY(lastMove.fromY));

        // 如果有被吃的棋子，恢复它
        if (lastMove.capturedPiece != null) {
            lastMove.capturedPiece.setVisible(true);
            pieceEntityList.add(lastMove.capturedPiece);
            container.add(lastMove.capturedPiece);
        }

        // 切换回合
        currentTurn = (currentTurn == RED) ? BLACK : RED;
        updateTurnDisplay();

        // 重新绘制界面
        container.revalidate();
        container.repaint();
    }

    private void offerDraw() {
        int choice = JOptionPane.showConfirmDialog(this,
            currentTurn == RED ? "黑方提出和棋，是否同意？" : "红方提出和棋，是否同意？",
            "和棋提议",
            JOptionPane.YES_NO_OPTION);
            
        if (choice == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(this, 
                "双方同意和棋，游戏结束！", 
                "游戏结束", 
                JOptionPane.INFORMATION_MESSAGE);
            resetGame();
        }
    }

    private void surrender() {
        int choice = JOptionPane.showConfirmDialog(this,
            "确定要投降吗？",
            "投降确认",
            JOptionPane.YES_NO_OPTION);
            
        if (choice == JOptionPane.YES_OPTION) {
            // 当前回合方投降，另一方获胜
            gameOver(currentTurn == RED ? BLACK : RED);
        }
    }

    private void resetGame() {
        int choice = JOptionPane.showConfirmDialog(this,
            "确定要重新开始游戏吗？",
            "重新开始",
            JOptionPane.YES_NO_OPTION);
            
        if (choice == JOptionPane.YES_OPTION) {
            // 清空历史记录
            moveHistory.clear();
            
            // 停止所有计时器
            if (timer != null && timer.isRunning()) {
                timer.stop();
            }
            if (blinkTimer != null && blinkTimer.isRunning()) {
                blinkTimer.stop();
            }
            
            // 重置选中状态
            clickedPiece = null;
            
            // 清除所有组件
            container.removeAll();
            
            // 重置回合
            currentTurn = RED;

            jToolBar.removeAll();
            // 重新初始化界面组件
            initToolBar();
            initPieces();
            setBackgroundImage();
            
            // 重新布局和绘制
            container.revalidate();
            container.repaint();
            
            // 重置计时器
            startCountdown();
        }
    }

    private void endGame() {
        int choice = JOptionPane.showConfirmDialog(this,
            "确定要退出游戏吗？",
            "退出游戏",
            JOptionPane.YES_NO_OPTION);
            
        if (choice == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }

    private void movePiece(PieceEntity piece, int targetX, int targetY) {
        // 记录移动前的位置和可能被吃的棋子
        int fromX = piece.getRow();
        int fromY = piece.getColumn();
        PieceEntity targetPiece = getPieceAtPosition(targetX, targetY);
        
        // 保存移动记录
        moveHistory.push(new MoveRecord(piece, fromX, fromY, targetX, targetY, targetPiece));

        if (targetPiece != null) {
            // 设置被吃的棋子不可见
            targetPiece.setVisible(false);
            // 从棋子列表中移除
            pieceEntityList.remove(targetPiece);
            // 如果是将/帅被吃，游戏结束
            if (targetPiece.getPieceName() == PieceNameEnum.KING || 
                targetPiece.getPieceName() == PieceNameEnum.GENERAL) {
                gameOver(piece.getPieceColorEnum());
                return;
            }
        }

        // 更新棋子位置
        piece.setRow(targetX);
        piece.setColumn(targetY);
        piece.setLocation(calculatePixelX(targetX), calculatePixelY(targetY));
        piece.setVisible(true);
        
        // 重新绘制界面
        backgroundJLabel.revalidate();
        backgroundJLabel.repaint();
        
        // 移动完成后重置计时器
        startCountdown();
    }

    private void gameOver(PieceColorEnum winnerColor) {
        // 停止计时器
        if (timer != null && timer.isRunning()) {
            timer.stop();
        }
        if (blinkTimer != null && blinkTimer.isRunning()) {
            blinkTimer.stop();
        }

        // 显示游戏结束对话框
        String winner = winnerColor == RED ? "红方" : "黑方";
        JOptionPane.showMessageDialog(this, 
            winner + "获胜！", 
            "游戏结束", 
            JOptionPane.INFORMATION_MESSAGE);

        // 可以在这里添加重新开始游戏的选项
        int choice = JOptionPane.showConfirmDialog(this,
            "是否要重新开始游戏？",
            "游戏结束",
            JOptionPane.YES_NO_OPTION);
            
        if (choice == JOptionPane.YES_OPTION) {
            initPieces(); // 重新初始化棋局
        }
    }

    private PieceEntity getPieceAtPosition(int x, int y) {

        // 遍历所有棋子，找到指定位置的棋子
        for (PieceEntity pieceEntity : pieceEntityList) {
            if (pieceEntity.getRow() == x && pieceEntity.getColumn() == y) {
                return pieceEntity;
            }

        }
        return null;
    }

    // 辅助方法：计算像素坐标
    private int calculatePixelX(int x) {
        // 根据实际棋盘尺寸计算
        return x * PIECE_SIZE + BOARD_OFFSET_X;
    }

    private int calculatePixelY(int y) {
        // 根据实际棋盘尺寸计算
        return y * PIECE_SIZE + BOARD_OFFSET_Y;
    }

}
